package demon1;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User:22954
 * Date:2024-01-12
 * Time:16:58
 */

import java.util.Arrays;

/**
 * clone虽然属于Object，但是类要使用一定要使用Cloneable接口
 * 必须重写一遍clone方法
 * Object类中的clone是protect修饰的，要用super.访问
 */
class Money implements Cloneable {
    float money;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

class Person implements Cloneable {
    int id = 1;
    Money money = new Money();

    public Person(int id, float money) {
        this.id = id;
        this.money.money = money;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        //return super.clone();  //浅拷贝
        /**
         * 深拷贝
         */
        Person tmp = (Person) super.clone();
        tmp.money = (Money) this.money.clone();
        return tmp;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", money=" + money.money +
                '}';
    }
}

public class Test2 {
    public static void main(String[] args) throws CloneNotSupportedException {
        /**
         * 浅拷贝，Person类中的money拷贝地址而不新开堆空间
         * 深拷贝，Person类中money的空间也重新开辟空间
         */
        Person person1 = new Person(12345, 100.0f);
        System.out.println(person1.toString());
        Person person2 = (Person) person1.clone();
        person2.money.money = 200.0f;
        System.out.println(person1.toString());
        System.out.println(person2.toString());
    }

    /**
     * @param args 不懂，要克隆一定要加上这个，位置不能变
     * @throws CloneNotSupportedException
     */
    public static void main2(String[] args) throws CloneNotSupportedException {
        Person person1 = new Person(12345, 100);
        System.out.println(person1.toString());
        Person person2 = (Person) person1.clone();
        System.out.println(person2.toString());


    }

    public static void main1(String[] args) {
        Object object = new Object();
        object.getClass().getName();
    }
}
